package com.canbot.u05.activity.presidemode;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;

import com.alibaba.fastjson.JSON;
import com.canbot.u05.R;
import com.canbot.u05.activity.presidemode.eventbus.AudioEvent;
import com.canbot.u05.adapter.HostModeChooseAudioListViewAdapter;
import com.canbot.u05.bean.Audio;
import com.canbot.u05.bean.JsonResponse;
import com.canbot.u05.socket.IpMsgConst;
import com.canbot.u05.socket.MsgSendUtils;
import com.canbot.u05.socket.MsgType;
import com.canbot.u05.utils.Logger;
import com.canbot.u05.utils.OkHttpUtils;
import com.canbot.u05.utils.ToastTools;
import com.canbot.u05.widget.LoadingDialogUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;

/**
 * @author zmp
 * 主持模式选择音频界面
 */
public class HostModeChooseAudioActivity extends BaseCompereActivity implements View.OnClickListener, AdapterView.OnItemClickListener{

        private Button btnBack;

        private Button btnSure;

        private GridView gridView;

        private List<Audio> data = new ArrayList<>();

        private HostModeChooseAudioListViewAdapter adapter;

        private Audio selectAudio;  //选择的音频

        private int lastPosition = -1;

        private Dialog dialogLoading;

        private int type;

        private String audioName;

        private String audioPath;


        @Override
        protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_host_mode_choose_audio);
                setViews();
                getData();
        }

        private void setViews() {
                Intent intent = getIntent();
                type = intent.getIntExtra("type", AudioEvent.AUDIO_TYPE_AUDIO);
                audioName = intent.getStringExtra("content");
                audioPath = intent.getStringExtra("path");
                btnBack = (Button) findViewById(R.id.btn_back);
                btnSure = (Button) findViewById(R.id.btn_right);
                gridView = (GridView) findViewById(R.id.host_mode_choose_audio_gridView);
                btnBack.setOnClickListener(this);
                btnSure.setOnClickListener(this);
                gridView.setOnItemClickListener(this);
                resultIntent = new Intent();
        }

        private void getData() {
                dialogLoading = LoadingDialogUtils.createLoadingDialog(HostModeChooseAudioActivity.this, getResources().getString(R.string.request));
                dialogLoading.show();
                String url = "http://" + IpMsgConst.HEAD_SOCKET_HOST + ":7755/getAudioList";
                HashMap<String, String> hashMap = new HashMap<>();
                hashMap.put("path", "/uusound");
                OkHttpUtils.upLoadFile(url, hashMap, new OkHttpUtils.OkHttpCallBack(){
                        @Override
                        public void onSuccess(String result) {
                                Log.e("t", result);
                                final JsonResponse strMsgBean = JSON.parseObject(result, JsonResponse.class);
                                Logger.e("save", "onSuccess:" + "http://" + IpMsgConst.HEAD_SOCKET_HOST + ":7755/" + "strMsgBean.getRc()" + strMsgBean.getRc());
                                if(strMsgBean.getRc() == 0) {
                                        runOnUiThread(new Runnable(){
                                                @Override
                                                public void run() {
                                                        dialogLoading.setCancelable(true);
                                                        dialogLoading.dismiss();
                                                        List<Audio> list = JSON.parseArray(strMsgBean.getResult().toString(), Audio.class);

                                                        Collections.sort(list, new Comparator<Audio>(){
                                                                @Override
                                                                public int compare(Audio audio, Audio t1) {
                                                                        return audio.getName().compareTo(t1.getName());
                                                                }
                                                        });
                                                        for(int i = 0; i < list.size(); i++) {
                                                                Audio audio = list.get(i);
                                                                if(!TextUtils.isEmpty(audioPath)) {
                                                                        if(type == AudioEvent.AUDIO_TYPE_AUDIO && audioPath.equals(audio.getPath())) {
                                                                                audio.setChecked(true);
                                                                                selectAudio = audio;
                                                                                lastPosition = i;
                                                                        }
                                                                }
                                                        }
                                                        setAdapter(list);
                                                        data.addAll(list);
                                                }
                                        });
                                }
                        }

                        @Override
                        public void onFailure() {
                                runOnUiThread(new Runnable(){
                                        @Override
                                        public void run() {
                                                dialogLoading.dismiss();
                                                ToastTools.newInstance(HostModeChooseAudioActivity.this).showText(getString(R.string.network_error));
                                        }
                                });
                        }
                });

        }

        private void setAdapter(List<Audio> data) {
                adapter = new HostModeChooseAudioListViewAdapter(this, data);
                gridView.setAdapter(adapter);
        }

        private Intent resultIntent;

        @Override
        public void onClick(View view) {
                switch(view.getId()) {
                        case R.id.btn_back:
                                finish();
                                overridePendingTransition(R.anim.face_zoom_enter, R.anim.face_zoom_exit);
                                break;

                        case R.id.btn_right:
                                //确定
                                if(selectAudio == null) {
                                        ToastTools.newInstance(HostModeChooseAudioActivity.this).showText(getString(R.string.please_select_audio));
                                        return;
                                }
                                resultIntent.putExtra("type", AudioEvent.AUDIO_TYPE_AUDIO);
                                resultIntent.putExtra("content", selectAudio.getName());
                                resultIntent.putExtra("path", selectAudio.getPath());
                                setResult(RESULT_OK, resultIntent);
                                finish();
                                overridePendingTransition(R.anim.face_zoom_enter, R.anim.face_zoom_exit);
                                break;
                }
        }

        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                if(data.get(position).isChecked()) {
                        data.get(position).setChecked(false);
                        adapter.updataView(position, gridView);
                        selectAudio = null;
                        //            stopVoice();
                        boolean isSuccess = MsgSendUtils.sendStringMsg(MsgType.STOP_SOUND, "stop");
                        if(!isSuccess) {
                                ToastTools.newInstance(HostModeChooseAudioActivity.this).showText(getString(R.string.network_error));
                        }
                } else {
                        data.get(position).setChecked(true);
                        adapter.updataView(position, gridView);
                        selectAudio = data.get(position);

//            playingVoice(selectAudio.getPath());
                        boolean isSuccess = MsgSendUtils.sendStringMsg(MsgType.PLAY_SOUND, selectAudio.getPath());
                        Logger.e("t", "播放路径==" + selectAudio.getPath());
                        if (!isSuccess) {

                                ToastTools.newInstance(HostModeChooseAudioActivity.this).showText(getString(R.string.network_error));
                        }
                }
                if(lastPosition != -1 && data.get(lastPosition).isChecked() && lastPosition != position) {
                        data.get(lastPosition).setChecked(false);
                        adapter.updataView(lastPosition, gridView);
                }
                lastPosition = position;
        }

        private void playingVoice(String path) {
                Logger.e("test", path);
                HashMap<String, Object> hasMap = new HashMap<>();
                hasMap.put("playVoice", path);
                OkHttpUtils.upLoadFile(IpMsgConst.HTTP_URL + "presenterMsg", hasMap, new OkHttpUtils.OkHttpCallBack(){
                        @Override
                        public void onSuccess(String result) {
                                Logger.e("save", "onSuccess:" + result);
                        }

                        @Override
                        public void onFailure() {
                                Logger.e("save", "onFailure");
                                runOnUiThread(new Runnable(){
                                        @Override
                                        public void run() {
                                                ToastTools.newInstance(HostModeChooseAudioActivity.this).showText(getString(R.string.network_error));
                                        }
                                });
                        }
                });
        }

        private void stopVoice() {
                HashMap<String, Object> hasMap = new HashMap<>();
                hasMap.put("stopVoice", "stopVoice");
                OkHttpUtils.upLoadFile(IpMsgConst.HTTP_URL_CHEST + "presenterMsg", hasMap, new OkHttpUtils.OkHttpCallBack(){
                        @Override
                        public void onSuccess(String result) {
                                Logger.e("save", "onSuccess:" + result);
                        }

                        @Override
                        public void onFailure() {
                                Logger.e("save", "onFailure");
                                runOnUiThread(new Runnable(){
                                        @Override
                                        public void run() {
                                                ToastTools.newInstance(HostModeChooseAudioActivity.this).showText(getString(R.string.network_error));
                                        }
                                });
                        }
                });
        }

        @Override
        protected void onPause() {
                boolean isSuccess = MsgSendUtils.sendStringMsg(MsgType.STOP_SOUND, "stop");
                if(!isSuccess) {
                        ToastTools.newInstance(HostModeChooseAudioActivity.this).showText(getString(R.string.network_error));
                }
                super.onPause();
        }
}
